package com.ciwong.epaper.modules.me.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.UserAccountInfo;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.util.AESCBCUtil;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.LogOutUtil;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.weakpassword.CheckPWD;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ModifyPasswordActivity extends BaseActivity {
    private EditText modifyPasswordCurrent, modifyPasswordNew,
            modifyPasswordConfirmNew;
    private Button mBtnConfirm;

    @Override
    protected int setView() {
        return R.layout.activity_modify_password;
    }

    @Override
    protected void findViews() {
        modifyPasswordCurrent = (EditText) findViewById(
                R.id.modify_password_current);
        modifyPasswordNew = (EditText) findViewById(
                R.id.modify_password_new);
        modifyPasswordConfirmNew = (EditText) findViewById(
                R.id.modify_password_confirm_new);
        mBtnConfirm = (Button) findViewById(
                R.id.btn_confirm);
    }

    @Override
    protected void initEvent() {
        mBtnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetworkUtils.isOnline()) {
                    verifyPassword();
                } else {
                    ToastUtil.INSTANCE.toastCenterNoNetError();
                }
            }
        });

    }

    @Override
    protected void init() {
        setTitleText(R.string.modify_password);
    }

    @Override
    protected void loadData() {

    }

    /**
     * 验证密码
     */
    private void verifyPassword() {
        final String modifyPasswordCurrentBerfor = this.modifyPasswordCurrent
                .getText().toString();
        final String modifyPasswordNewBerfor = this.modifyPasswordNew.getText()
                .toString();
        String modifyPasswordConfirmNew = this.modifyPasswordConfirmNew
                .getText().toString();
        if (TextUtils.isEmpty(modifyPasswordCurrentBerfor)) {
            showToastError(R.string.current_password_error);
        } else if (!modifyPasswordNewBerfor.equals(modifyPasswordConfirmNew)) {
            showToastError(R.string.pass_not_same);
        } else if (!MeUtil.validatePassword(modifyPasswordNewBerfor)) {
            showToastError(R.string.register_password_hint_fail);
        } else if (!CheckPWD.EvalPWD(modifyPasswordNewBerfor)) {
            showPasswordDialog(modifyPasswordCurrentBerfor, modifyPasswordNewBerfor);
        } else {
            modifyPossword(modifyPasswordCurrentBerfor, modifyPasswordNewBerfor);
        }
    }

    /**
     * 修改密码
     *
     * @param modifyPasswordCurrentBerfor
     * @param modifyPasswordNewBerfor
     */
    private void modifyPossword(String modifyPasswordCurrentBerfor, String modifyPasswordNewBerfor) {
        showMiddleProgressBar(getTitleText());
        final String modifyPasswordCurrent = AESCBCUtil.encrypt(modifyPasswordCurrentBerfor, AESCBCUtil.AESCBC_HEX);
        final String modifyPasswordNew = AESCBCUtil.encrypt(modifyPasswordNewBerfor, AESCBCUtil.AESCBC_HEX);
        MeDao.getInstance().modifyPossword(modifyPasswordCurrent,
                modifyPasswordNew, new BaseExtCallBack(ModifyPasswordActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
//                            DialogUtil.showFailedToastByErrorType(ModifyPasswordActivity.this,data);
                        if (errorCode == 100) {
                               /* CWToast.makeText(ModifyPasswordActivity.this, String.valueOf(data), Toast.LENGTH_LONG, true)
                                        .setToastType(CWToast.TOAST_TYPE_ERROR).show();*/
                            showToastError(String.valueOf(data));
                        }
                        hideMiddleProgressBar();
                    }

                    @Override
                    public void failed(Object data) {
                        DialogUtil.showFailedToastByErrorType(ModifyPasswordActivity.this, data);
                        hideMiddleProgressBar();
                    }

                    @Override
                    public void success(Object data) {

                        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                                new BaseCallBack() {
                                    @Override
                                    public void success(Object data) {

                                        List<UserAccountInfo> userAccountList;
                                        userAccountList = (ArrayList<UserAccountInfo>) data;

                                        if (null != userAccountList && userAccountList.size() > 0) {
                                            for (int i = 0; i < userAccountList.size(); i++) {
                                                if (userAccountList.get(i).getUserId() == EApplication.getInstance().getUserInfoBase().getUserId()) {
                                                    userAccountList.get(i).setUserPwd(modifyPasswordNew);
                                                    break;
                                                }
                                            }

                                            SerializableManager.getInstance().serialize(
                                                    SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                                                    (Serializable) userAccountList, false);
                                        }
                                    }

                                    @Override
                                    public void failed(int errorCode, Object data) {

                                    }

                                    @Override
                                    public void failed(Object data) {

                                    }
                                }, false);

                        showModifyPasswordHint();
                        hideMiddleProgressBar();
                    }
                });
    }
//    /**
//     * 修改当前登录账号信息
//     */
//    private void modifyCurrentLoginInfo()
//    {
//        SerializableManager.getInstance().deSerialize(
//                SerializableManager.SerializeKey.SHARE_KEY_LOGIN_ACCOUNT_LIST,
//                new BaseCallBack()
//                {
//
//                    @Override
//                    public void failed(int errorCode, Object data)
//                    {
//                        showModifyPasswordHint();
//                        hideMiddleProgressBar();
//                    }
//
//                    @Override
//                    public void failed(Object data)
//                    {
//                        showModifyPasswordHint();
//                        hideMiddleProgressBar();
//                    }
//
//                    @Override
//                    public void success(Object data)
//                    {
//                        List<LoginAccountInfo> loginAccountInfos = (List<LoginAccountInfo>) data;
//                        if (loginAccountInfos != null
//                                && !loginAccountInfos.isEmpty())
//                        {
//                            LoginAccountInfo remove = loginAccountInfos
//                                    .remove(0);
//                            remove.setUserPwd("");
//                            loginAccountInfos.add(0, remove);
//                            SerializableManager.getInstance().serialize(
//                                    SerializableManager.SerializeKey.SHARE_KEY_LOGIN_ACCOUNT_LIST,
//                                    (Serializable) loginAccountInfos, false);
//
//                            //存入新的用户登录结构数据
//                            List<UserAccountInfo> userAccountInfoList=new ArrayList<UserAccountInfo>();
//                            for (LoginAccountInfo loginAccountInfo:loginAccountInfos){
//                                UserAccountInfo userAccountInfo=new UserAccountInfo();
//                                userAccountInfo.setUserId(loginAccountInfo.getUserId());
//                                userAccountInfo.setAvatar(loginAccountInfo.getAvatar());
//                                userAccountInfo.setUserPwd(loginAccountInfo.getUserPwd());
//                               /* userAccountInfo.setPhonelogin(loginAccountInfo.getPhonelogin());
//                                userAccountInfo.setPhoneNumber(loginAccountInfo.getPhoneNumber())*/;
//                                userAccountInfoList.add(userAccountInfo);
//                            }
//                            SerializableManager.getInstance().serialize(
//                                    SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
//                                    (Serializable) userAccountInfoList, false);
//
//
//
//                        }
//                        showModifyPasswordHint();
//                        hideMiddleProgressBar();
//                    }
//                }, false);
//    }

    /**
     * 修改密码成功提示
     */
    private void showModifyPasswordHint() {
        final CWDialog dialog = new CWDialog(this);
        dialog.setCancelable(false);
        dialog.setMessage(R.string.modify_password_success);
        dialog.setPositiveButton(getString(android.R.string.ok),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface interDialog,
                                        int which) {
                        executeOtherThread(new Runnable() {
                            @Override
                            public void run() {
                                LogOutUtil.logOut(ModifyPasswordActivity.this);
                            }
                        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);

                    }
                }, true,
                getResources().getDrawable(R.drawable.dialog_floor_selector));
        dialog.show();
    }

    private CWDialog cWPasswordDialog;

    /**
     * 密码简单提示
     */
    private void showPasswordDialog(final String modifyPasswordCurrentBerfor, final String modifyPasswordNewBerfor) {
        String msgTips = getString(R.string.dialog_passwore_tips);
        if (cWPasswordDialog != null && cWPasswordDialog.isShowing()) {
            cWPasswordDialog.dismiss();
        }
        cWPasswordDialog = new CWDialog(this);
        cWPasswordDialog.setMessagWidePadding(msgTips).setPositiveButton("继续", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                cWPasswordDialog.dismiss();
                modifyPossword(modifyPasswordCurrentBerfor, modifyPasswordNewBerfor);
            }
        }).setNegativeButton("重新设置", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                cWPasswordDialog.dismiss();
            }
        }).setNegativeButtonTextColor(com.ciwong.mobilelib.R.color.color_light_green).show();

        cWPasswordDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                cWPasswordDialog.dismiss();
            }
        });
    }
}
